﻿using System.Linq;
using System.Web.Mvc;
using JStore.Core.Commands;
using JStore.Core.Entities;
using JStore.Tasks;
using JStore.Web.Controllers.UserTypes.ViewModels;
using SpeadFrm.Mappers;

namespace JStore.Web.Controllers.UserTypes
{
    public class UserTypesController : BaseController
    {
        private readonly UserTypeTask _userTypeTask = new UserTypeTask();

        public ActionResult List()
        {
            var model = _userTypeTask.GetAll().Select(EntityMapper.Map<UserType, UserTypeModel>).ToList();
            return View(model);
        }

        public ActionResult Save(int? id)
        {
            var model = new SaveUserTypeModel();
            if (id != null)
            {
                var info = _userTypeTask.GetById((int)id);
                if (info != null)
                    model = EntityMapper.Map<UserType, SaveUserTypeModel>(info);
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult Save(SaveUserTypeModel model)
        {
            if (ModelState.IsValid)
            {
                var cmd = EntityMapper.Map<SaveUserTypeModel, SaveUserTypeCmd>(model);
                string errMsg;
                if (!_userTypeTask.Save(cmd, out errMsg))
                    return AlertMsg(errMsg, Request.UrlReferrer.PathAndQuery);
                return AlertMsg("保存成功", Request.UrlReferrer.PathAndQuery);
            }
            return AlertMsg("参数不正确", Request.UrlReferrer.PathAndQuery);
        }

        [HttpPost]
        public void Delete(int id)
        {
            _userTypeTask.DeleteById(id);
        }
    }
     
}